import type { MockMethod } from 'vite-plugin-mock'
import { cve_list, host_list_in_vul, repos, tasks } from '../contants'

interface Response<T = any> {
  code: number
  data: T
  label: string
  message: string
}
// #region ------------------------------------ < distribution > ------------------------------------
const generateCveTask: MockMethod = {
  url: '/api/distribute/task/cve-fix/generate',
  method: 'post',
  timeout: 300,
  response: () => {
    return {
      code: 200,
      data: [{ fix_way: 'coldpatch', task_id: '0b6a992a141711efb93352540031faec' }],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const generateCveHotPatchTask: MockMethod = {
  url: '/api/distribute/task/hotpatch-remove/generate',
  method: 'post',
  timeout: 1000,
  response: () => {
    return {
      code: 200,
      data: [{ fix_way: 'coldpatch', task_id: '0b6a992a141711efb93352540031faec' }],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const generateRepoSetTask: MockMethod = {
  url: '/api/distribute/vulnerabilities/task/repo/generate',
  method: 'post',
  timeout: 200,
  response: () => {
    return {
      code: 200,
      data: { task_id: '0b6a992a141711efb93352540031faec' },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const scanHost: MockMethod = {
  url: '/api/distribute/host/scan',
  method: 'post',
  timeout: 1000,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const deleteTasks: MockMethod = {
  url: '/api/distribute/task/delete',
  method: 'delete',
  timeout: 400,
  response: ({ body }) => {
    const taskIds = Object.values(body).flatMap(cluster => cluster.task_list)
    taskIds.forEach((id: string) => {
      const taskInd = tasks.findIndex(item => item.task_id === id)
      if (taskInd > -1)
        tasks.splice(taskInd, 1)
    })

    return {
      code: 200,
      data: {
        running_task: [],
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const executeTask: MockMethod = {
  url: '/api/distribute/task/execute',
  method: 'post',
  timeout: 400,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const generateCveRollbackTask: MockMethod = {
  url: '/api/distribute/task/cve-rollback/generate',
  method: 'post',
  timeout: 500,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const createNewRepo: MockMethod = {
  url: '/api/distribute/vulnerabilities/repo/import',
  method: 'post',
  timeout: 500,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
// #endregion

const exportCveInfo: MockMethod = {
  url: '/api/cve/info/export',
  method: 'post',
  timeout: 1000,
  response: () => {
    const data = JSON.stringify({ message: 'Hello, this is a Blob!' })
    return new Blob([data], { type: 'application/json' })
  },
}
const getHostStatus: MockMethod = {
  url: '/api/vulnerabilities/host/status/get',
  method: 'post',
  timeout: 500,
  response: ({ body }) => {
    const { host_list } = body
    const list = host_list.length !== 0 ? host_list : host_list_in_vul.map(i => i.host_id)

    const result = {}
    list.forEach((id: string) => {
      result[id] = Math.random() < 0.5 ? 0 : 3
    })
    return {
      code: 200,
      data: {
        result,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * upload SA which is affected
 */
const uploadSAAffected: MockMethod = {
  url: '/api/cve/advisory/upload',
  method: 'post',
  timeout: 2000,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * upload SA which is unaffected
 */
const uploadSAUnAffected: MockMethod = {
  url: '/api/cve/unaffected/upload',
  method: 'post',
  timeout: 2000,
  response: () => {
    return {
      code: 200,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * get cve overview info
 */
const getCveOverview: MockMethod = {
  url: '/api/vulnerabilities/cve/overview',
  method: 'get',
  response: () => {
    return {
      code: 200,
      data: {
        result: {
          Critical: 0,
          High: 48,
          Low: 12,
          Medium: 110,
          Unknown: 0,
        },
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * get cve list
 */
const getCves: MockMethod = {
  url: '/api/vulnerabilities/cve/list/get',
  timeout: 200,
  method: 'post',
  response: ({ body }) => {
    const { page, per_page, filter } = body
    const { search_key } = filter

    const filteredCves = cve_list.filter((item) => {
      if (!search_key)
        return true
      return item.cve_id.includes(search_key)
    })
    const paginationCves
      = page && per_page ? filteredCves.slice((page - 1) * per_page, page * per_page) : filteredCves
    return {
      code: 1207,
      data: {
        result: paginationCves,
        total_count: filteredCves.length,
        total_page: Math.ceil(filteredCves.length / per_page),
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * get hosts in cves
 */
const getHostsInCve: MockMethod = {
  url: '/api/vulnerabilities/cve/task/host/get',
  timeout: 200,
  method: 'post',
  response: ({ body }) => {
    const { cve_list: list } = body
    const result = {}
    let num = 1
    list.forEach(({ cve_id }) => {
      result[cve_id] = {
        hosts: [
          {
            host_id: `host${num}`,
            host_ip: '172.168.185.234',
            host_name: '172.168.185.234',
            cluster_id: 'cluster1',
            cluster_name: '集群1',
            hotpatch: true,
          },
          {
            host_id: `host${num + 1}`,
            host_ip: '172.168.185.235',
            host_name: '172.168.185.235',
            cluster_id: 'cluster2',
            cluster_name: '集群2',
            hotpatch: true,
          },
        ],
        package: 'kernel',
      }
      num += 2
    })
    return {
      code: 200,
      data: {
        result,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getCvesWithHost: MockMethod = {
  url: '/api/vulnerabilities/host/cve/get',
  timeout: 200,
  method: 'post',
  response: ({ body }) => {
    const { page, per_page, filter } = body
    const { search_key } = filter

    const filteredCves = cve_list.filter((item) => {
      if (!search_key)
        return true
      return item.cve_id.includes(search_key)
    })

    const paginationCves
      = page && per_page ? filteredCves.slice((page - 1) * per_page, page * per_page) : filteredCves
    return {
      code: 200,
      data: {
        result: paginationCves.map(item => ({
          cve_id: item.cve_id,
          cvss_score: item.cvss_score,
          description: item.description,
          package: item.package,
          publish_time: item.publish_time,
          severity: item.severity,
        })),
        total_count: filteredCves.length,
        total_page: Math.ceil(filteredCves.length / per_page),
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getUnfixedRpm: MockMethod = {
  url: '/api/vulnerabilities/cve/unfixed/packages/get',
  timeout: 200,
  method: 'post',
  response: () => {
    return {
      code: 200,
      data: [
        {
          available_rpm: 'kernel-5.10.0-183.0.0.96.oe2203sp3.aarch64',
          host_num: 1,
          installed_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
          support_way: 'coldpatch',
        },
        {
          available_rpm: 'kernel-5.10.0-183.0.0.96.oe2203sp3.aarch64',
          host_num: 2,
          installed_rpm: 'kernel-5.10.0-182.0.0.95.oe2203sp3.aarch64',
          support_way: 'hotpatch',
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const getFixedRpm: MockMethod = {
  url: '/api/vulnerabilities/cve/fixed/packages/get',
  timeout: 200,
  method: 'post',
  response: () => {
    return {
      code: 200,
      data: [
        {
          fixed_way: 'hotpatch',
          host_num: 1,
          installed_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
          hp_status: 'ACTIVED',
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

/**
 * get cve dettail mock request
 */
const getCveDetail: MockMethod = {
  url: '/api/vulnerabilities/cve/info/get',
  method: 'get',
  timeout: 200,
  response: (): Response<{ result: any }> => {
    return {
      code: 200,
      data: {
        result: {
          cve_id: 'CVE-2021-33631',
          cvss_score: '5.5',
          description: 'openeuler-linux-kernel-5.10.149-ext4_write_inline_data-kernel_bug-365020',
          package: [
            {
              os_version: 'openEuler-20.03-LTS-SP1',
              package: 'kernel',
            },
            {
              os_version: 'openEuler-20.03-LTS-SP4',
              package: 'kernel',
            },
            {
              os_version: 'openEuler-22.03-LTS',
              package: 'kernel',
            },
            {
              os_version: 'openEuler-22.03-LTS-SP1',
              package: 'kernel',
            },
            {
              os_version: 'openEuler-22.03-LTS-SP2',
              package: 'kernel',
            },
            {
              os_version: 'openEuler-22.03-LTS-SP3',
              package: 'kernel',
            },
          ],
          publish_time: '2024-01-12',
          related_cve: Array.from({ length: 108 }, (_, index) => index + 1).map(
            item => `CVE-2021-469${item}`,
          ),
          severity: 'Medium',
        },
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
/**
 * get host list by cve id request mock
 */
const getHostByCveId: MockMethod = {
  url: '/api/vulnerabilities/cve/host/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: {
        result: [
          {
            host_id: 'host1',
            host_ip: '172.168.185.234',
            host_name: '172.168.185.234',
            host_group: 'aops',
            repo: null,
            last_scan: 1713985200,
            cluster_id: 'cluster1',
            cluster_name: '集群1',
          },
          {
            host_id: 'host2',
            host_ip: '172.168.185.235',
            host_name: '172.168.185.235',
            host_group: 'aops',
            repo: null,
            last_scan: 1713985200,
            cluster_id: 'cluster2',
            cluster_name: '集群2',
          },
        ],
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getHostsInVul: MockMethod = {
  url: '/api/vulnerabilities/host/list/get',
  method: 'post',
  timeout: 200,
  response: ({ body }): Response => {
    const { page, per_page } = body
    const paginationHosts
      = !page || !per_page
        ? host_list_in_vul
        : host_list_in_vul.slice((page - 1) * per_page, page * per_page)
    return {
      code: 1207,
      data: {
        result: paginationHosts,
        total_count: host_list_in_vul.length,
        total_page: Math.ceil(host_list_in_vul.length / per_page),
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getCveRepoList: MockMethod = {
  url: '/api/vulnerabilities/repo/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: repos,
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getHostInfo: MockMethod = {
  url: '/api/vulnerabilities/host/info/get',
  method: 'get',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: {
        result: {
          affected_cve_num: 108,
          fixed_cve_num: 0,
          host_group: 'aops',
          host_ip: '172.168.185.234',
          host_name: '172.168.185.234',
          last_scan: 1713985200,
          reboot: true,
          repo: null,
          unaffected_cve_num: 0,
        },
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getHostsAffectedByRpm: MockMethod = {
  url: '/api/vulnerabilities/cve/packages/host/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: {
        result: [
          {
            host_ip: '172.168.185.234',
            host_name: '172.168.185.234',
          },
        ],
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getTasks: MockMethod = {
  url: '/api/vulnerabilities/task/list/get',
  method: 'post',
  timeout: 200,
  response: ({ body }): Response => {
    const { page, per_page, filter } = body

    let filteredTasks = tasks
    if (filter.task_type && filter.task_type.length > 0)
      filteredTasks = filteredTasks.filter(item => filter.task_type.includes(item.task_type))

    const paginationTasks
      = page && per_page
        ? filteredTasks.slice((page - 1) * per_page, page * per_page)
        : filteredTasks
    return {
      code: 200,
      data: {
        result: paginationTasks.map(
          ({
            task_id,
            task_name,
            task_type,
            create_time,
            description,
            host_num,
            cluster_id,
            cluster_name,
          }) => ({
            create_time,
            description,
            host_num,
            task_id,
            task_name,
            task_type,
            cluster_id,
            cluster_name,
          }),
        ),
        total_count: filteredTasks.length,
        total_page: Math.floor(filteredTasks.length / 10),
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getTasksStatus: MockMethod = {
  url: '/api/vulnerabilities/task/progress/get',
  method: 'post',
  timeout: 200,
  response: ({ body }): Response => {
    const { task_list } = body
    const taskList = tasks.filter(item => task_list.includes(item.task_id))
    const result = {}

    taskList.forEach((item) => {
      const random = Math.floor(Math.random() * 4)
      const status = {}
      Object.keys(item.status).forEach((key, index) => {
        status[key] = Number(random === index)
      })

      result[item.task_id] = status
    })
    return {
      code: 200,
      data: {
        result,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getTaskDetailInfo: MockMethod = {
  url: '/api/vulnerabilities/task/info/get',
  method: 'get',
  timeout: 200,
  response: ({ query }): Response => {
    const { task_id } = query

    const { host_num, description, task_name } = tasks.find(item => item.task_id === task_id)!

    return {
      code: 200,
      data: {
        result: {
          accept: false,
          description,
          cluster_id: 'cluster1',
          clutser_name: '集群1',
          host_num,
          latest_execute_time: 1713985200,
          takeover: false,
          task_name,
        },
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const taskStatus = ['succeed', 'fail', 'running', 'unknown']

const getCveFixInfo: MockMethod = {
  url: '/api/vulnerabilities/task/cve-fix/info/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    const random = Math.floor(Math.random() * 4)
    return {
      code: 200,
      data: {
        result: [
          {
            cve_num: 1,
            host_id: 6,
            host_ip: '172.168.45.177',
            host_name: '172.168.45.177(22.03SP2)',
            status: taskStatus[random],
          },
        ],
        total_count: 1,
        total_page: 1,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getCveFixRpm: MockMethod = {
  url: '/api/task/cve-fix/rpm/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: [
        {
          available_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
          cves: 'CVE-2023-3389,CVE-2023-3390,CVE-2023-3391',
          installed_rpm: 'kernel-5.10.0-153.12.0.92.oe2203sp2.aarch64',
          status: 'succeed',
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getHotPatchInfo: MockMethod = {
  url: '/api/task/hotpatch-remove/info/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    const random = Math.floor(Math.random() * 4)
    return {
      code: 200,
      data: {
        result: [
          {
            cve_id: 'CVE-2021-33631',
            host_num: 1,
            package: 'kernel',
            status: taskStatus[random],
          },
        ],
        total_count: 1,
        total_page: 1,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const getCveRollbackInfo: MockMethod = {
  url: '/api/task/cve-rollback/info/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    const random = Math.floor(Math.random() * 4)
    return {
      code: 200,
      data: {
        result: [
          {
            cve_num: 'CVE-2021-33631',
            host_id: 'host1',
            host_ip: '129.13.4.13',
            host_name: '主机1号',
            status: taskStatus[random],
          },
        ],
        total_count: 1,
        total_page: 1,
      },
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const getCveRollbackRpm: MockMethod = {
  url: '/api/task/cve-rollback/rpm/get',
  method: 'post',
  timeout: 400,
  response: () => {
    return {
      code: 200,
      data: [
        {
          target_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
          cves: 'CVE-2023-3389,CVE-2023-3390,CVE-2023-3391',
          installed_rpm: 'kernel-5.10.0-153.12.0.92.oe2203sp2.aarch64',
          status: 'succeed',
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

const getCveRollbackTaskResult: MockMethod = {
  url: '/distribute/task/cve-rollback/result/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: [
        {
          host_id: 6,
          host_ip: '172.168.45.177',
          host_name: '172.168.45.177(22.03SP2)',
          latest_execute_time: 1714384568,
          status: 'succeed',
          task_id: 'aa1adcf4060e11efb93352540031faec',
          task_type: 'cve fix',
          task_result: {
            check_items: [
              { item: 'aaa', result: true },
              { item: 'bbb', result: false },
            ],
            dnf_event_end: 142,
            dnf_event_start: 141,
            rpms: [
              {
                available_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
                log: 'Last metadata expiration check: 0:16:29 ago on Mon 29 Apr 2024 05:39:36 PM CST.\nDependencies resolved.\n================================================================================\n Package                                        Arch     Version\n                                                                Repo       Size\n================================================================================\nInstalling:\n patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC  aarch64  1-1    hotpatch   13 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 13 k\nInstalled size: 24 k\nDownloading Packages:\npatch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1 103 kB/s |  13 kB     00:00    \n--------------------------------------------------------------------------------\nTotal                                           102 kB/s |  13 kB     00:00     \nRunning transaction check\nTransaction check succeeded.\nRunning transaction test\nTransaction test succeeded.\nRunning transaction\n  Preparing        :                                                        1/1 \n  Installing       : patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n  Running scriptlet: patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n  Verifying        : patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n\nInstalled:\n  patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64                     \n\nComplete!\nApply hot patch succeed: kernel-5.10.0-153.12.0.92.oe2203sp2/ACC-1-1.',
                result: 'succeed',
              },
            ],
          },
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}
const getTaskResult: MockMethod = {
  url: '/api/distribute/task/cve-fix/result/get',
  method: 'post',
  timeout: 200,
  response: (): Response => {
    return {
      code: 200,
      data: [
        {
          host_id: 6,
          host_ip: '172.168.45.177',
          host_name: '172.168.45.177(22.03SP2)',
          latest_execute_time: 1714384568,
          status: 'succeed',
          task_id: 'aa1adcf4060e11efb93352540031faec',
          task_type: 'cve fix',
          task_result: {
            check_items: [
              { item: 'aaa', result: true },
              { item: 'bbb', result: false },
            ],
            dnf_event_end: 142,
            dnf_event_start: 141,
            rpms: [
              {
                available_rpm: 'patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64',
                log: 'Last metadata expiration check: 0:16:29 ago on Mon 29 Apr 2024 05:39:36 PM CST.\nDependencies resolved.\n================================================================================\n Package                                        Arch     Version\n                                                                Repo       Size\n================================================================================\nInstalling:\n patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC  aarch64  1-1    hotpatch   13 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 13 k\nInstalled size: 24 k\nDownloading Packages:\npatch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1 103 kB/s |  13 kB     00:00    \n--------------------------------------------------------------------------------\nTotal                                           102 kB/s |  13 kB     00:00     \nRunning transaction check\nTransaction check succeeded.\nRunning transaction test\nTransaction test succeeded.\nRunning transaction\n  Preparing        :                                                        1/1 \n  Installing       : patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n  Running scriptlet: patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n  Verifying        : patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aa   1/1 \n\nInstalled:\n  patch-kernel-5.10.0-153.12.0.92.oe2203sp2-ACC-1-1.aarch64                     \n\nComplete!\nApply hot patch succeed: kernel-5.10.0-153.12.0.92.oe2203sp2/ACC-1-1.',
                result: 'succeed',
              },
            ],
          },
        },
      ],
      label: 'Succeed',
      message: 'operation succeed',
    }
  },
}

export const vulnerabilityMock: Array<MockMethod> = [
  getCves,
  getCvesWithHost,
  getUnfixedRpm,
  getCveDetail,
  getHostByCveId,
  getHostsInVul,
  getFixedRpm,
  getCveRepoList,
  getHostInfo,
  getHostsAffectedByRpm,
  getTasks,
  deleteTasks,
  getTasksStatus,
  getTaskDetailInfo,
  getCveFixInfo,
  getCveFixRpm,
  getTaskResult,
  getCveOverview,
  uploadSAAffected,
  uploadSAUnAffected,
  getHostsInCve,
  generateCveTask,
  generateCveHotPatchTask,
  getHostStatus,
  scanHost,
  exportCveInfo,
  executeTask,
  getHotPatchInfo,
  generateCveRollbackTask,
  getCveRollbackInfo,
  getCveRollbackRpm,
  getCveRollbackTaskResult,
  generateRepoSetTask,
  createNewRepo,
]
